package com.orange.cetback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orange.cetback.common.constant.JwtClaimsConstant;
import com.orange.cetback.common.properties.JwtProperties;
import com.orange.cetback.common.utils.JwtUtil;
import com.orange.cetback.pojo.entity.Admin;
import com.orange.cetback.mapper.AdminMapper;
import com.orange.cetback.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员信息表 服务实现类
 * </p>
 *
 * @author chenenjun
 * @since 2025-03-09
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public String login(Admin admin) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,admin.getUsername());
        queryWrapper.eq(Admin::getPassword,admin.getPassword());
        Admin compare = this.getOne(queryWrapper);
        if (compare != null){
            //为管理员生成jwt令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID,compare.getId());
            return JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);
        }
        return null;
    }

    @Override
    public Admin getAdmin(String token) {
        if (token != null){
            Map<String, Object> map = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            if (map != null){
                Long id = Long.valueOf(map.get(JwtClaimsConstant.USER_ID).toString());
                return this.getById(id);
            }
        }
        return null;
    }
}
